package edu.ncut.vod.jsf.examonline.selfmadevalidator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

public class PasswordValidator implements Validator {

    /**
     * validate field 'password':its length can not be long than 12
     */
    public void validate(FacesContext context, UIComponent component,
            Object obj) throws ValidatorException {
        debug("method validate in class PasswordValidator is called");

        String label = ((HtmlInputSecret) component).getLabel();

        if("password".equals(label)){
            String fieldValue = (String) obj;   // get the value of field which needs validating

            //?fieldValue????
            if(fieldValue.length() > 12){
                FacesContext facesContext = FacesContext.getCurrentInstance();
                FacesMessage msg=MessageFactory.getMessage(facesContext,"passwordLength_smaller","passwordLength_smaller");
                msg.setSeverity(FacesMessage.SEVERITY_WARN);
                facesContext.addMessage("login:password",msg);
                throw new ValidatorException(msg);
            }
        }
    }

    /**
     * print message on console
     * @param message
     */
    public void debug(String message){
        System.out.println(message);
    }
}
